#! /usr/bin/python3
# -*- coding: UTF-8 -*-

if __name__ == "__main__":
	raise Exception("不支持从这里调用")

__version__ = "1.0"
__all__ = ["MouseChshMqServer"]

import time
from inspect import isfunction

from com.mousechsh.common.log.MouseChshLog import mousechsh_logging, mousechsh_logging_data, mousechsh_logging_exception
from com.mousechsh.common.sys.MouseChshThread import mousechsh_thread_annotation, mousechsh_thread_sleep


class MouseChshMqServer:

	def __init__(self):
		self.__default = 'MouseChshMqServer'
		self.__run = False
		self.__loop = False
		self.__index = 0
		self.__queen = []
		self.__data = {}

	def add(self, data, func):
		if data is None:
			return
		if not isfunction(func):
			return
		mousechsh_logging_data(data, "添加进程内服务端要处理的数据")
		data = str(data)
		index = self.__index
		self.__index += 1
		item = {
			index: index,
			data: data,
			func: func
		}
		self.__queen.append(index)
		self.__data[index] = item
		if self.__run and not self.__loop:
			mousechsh_inner_server_processing(self)

	def pop(self):
		if len(self.__queen) == 0:
			return None
		index = self.__queen.pop()
		if index is None:
			return None
		item = self.__data.pop(index, None)
		return item

	def loop_start(self):
		self.__loop = True

	def loop_stop(self):
		self.__loop = False

	def get_loop(self):
		return self.__loop

	def get_run(self):
		return self.__run

	def run(self):
		self.__run = True
		mousechsh_inner_server_processing(self)

	def proc(self, request):
		return self.__default

	def close(self):
		self.__run = False
		self.__loop = False


@mousechsh_thread_annotation(name='mousechsh_inner_server_processing')
def mousechsh_inner_server_processing(server):
	if server.get_loop():
		return
	server.loop_start()
	mousechsh_logging("进程内服务端处理已开始")
	while server.get_run() and server.get_loop():
		try:
			obj = server.pop()
			if obj is None:
				break
			mousechsh_logging_data(obj.data, "开始处理编号【", obj.index, "】的请求，请求内容：")
			timer = time.time()
			data = server.proc(obj.data)
			obj.func(data)
			mousechsh_logging_data(
				data, "完成对编号【", obj.index, "】的响应，用时【", ('%0.6f' % (time.time() - timer)), "】，响应内容："
			)
		except Exception as ex:
			mousechsh_logging_exception(ex, "进程内服务端在执行处理代码时遇到错误：")
			mousechsh_thread_sleep()
	mousechsh_logging("进程内服务端处理已结束")
	server.loop_stop()
